package org.dizena.modules.guest.web;

import com.google.code.kaptcha.Producer;
import org.dizena.common.pojo.master.ImgCodeVO;
import org.dizena.common.pojo.master.LoginVO;
import org.dizena.common.realm.JwtUtil;
import org.dizena.modules.guest.entity.LoginDto;
import org.dizena.modules.master.bean.User;
import org.dizena.modules.master.service.MenuService;
import org.dizena.modules.master.service.UserService;
import org.dizena.modules.master.zload.ConstantMaster;
import org.dizena.utils.IdGen;
import org.dizena.utils.RedisUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.util.Base64Utils;
import org.springframework.util.DigestUtils;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 游客注册登录
 */
@RestController
@RequestMapping("/api/v1/guest")
public class ApiGuestController {
    @Resource
    private UserService service;
    @Resource
    private MenuService menuService;
    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;
    @Resource
    private RedisUtil<String> redisUtilString;

    /**
     * 无权限
     */
    @RequestMapping("login")
    public String login() {
        return "请登录";
    }

    /**
     * 无权限
     */
    @RequestMapping("none")
    public String none() {
        return "没有访问权限";
    }

    /**
     * 初始测试
     */
    @GetMapping("init")
    public String init() {
        menuService.initMenu();
        return "请登录";
    }

    /**
     * 获取验证码
     */
    @GetMapping("image")
    public ImgCodeVO image() throws IOException {
        //生成文字验证码
        String text = captchaProducerMath.createText();
        //个位数字相加
        String s1 = text.substring(0, 1);
        String s2 = text.substring(1, 2);
        Integer code = Integer.parseInt(s1) + Integer.parseInt(s2);

        String uuid = IdGen.get().nextIdS();
        String key = "login:image:" + uuid;
        redisUtilString.add(key, code + "", 60);
        BufferedImage image = captchaProducerMath.createImage(s1 + "+" + s2 + "=?");
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        ImageIO.write(image, "jpg", os);
        ImgCodeVO vo = new ImgCodeVO();
        vo.setUuid(uuid);
        vo.setImage("data:image/gif;base64," + Base64Utils.encodeToString(os.toByteArray()));
        return vo;
    }

    /**
     * 登录获取token
     */
    @PostMapping("login")
    public LoginVO login(@Validated LoginDto dto) {
        String key = "login:image:" + dto.getUuid();
        String tmp = redisUtilString.get(key);
        if (tmp == null) {
            throw new RuntimeException("验证码已经过期");
        }
        if (!tmp.equals(dto.getCode())) {
            throw new RuntimeException("验证码输入错误");
        }
        redisUtilString.delete(key);

        User user = service.login(dto.getAccount());
        if (user != null) {
            if (user.getLocked().equals(ConstantMaster.LOCKED)) {
                throw new RuntimeException("账户被锁定了");
            }
            if (user.getLocked().equals(ConstantMaster.CLOSE)) {
                throw new RuntimeException("账户被注销了");
            }
            String passwd = DigestUtils.md5DigestAsHex((user.getSalt() + dto.getPassword()).getBytes(StandardCharsets.UTF_8));
            if (passwd.equals(user.getPasswd())) {
                LoginVO vo = new LoginVO();
                BeanUtils.copyProperties(user, vo);
                vo.setToken(JwtUtil.sign(dto.getAccount(), user.getPasswd()));
                return vo;
            }
        }
        throw new RuntimeException("账户或者密码错误");
    }

}
